<template>
  <!-- 页面容器：统一居中+背景色，提升整体质感 -->
  <div class="gesture-page-container">
    <!-- 页面主标题：居中显示，强化主题 -->
    <div class="page-header">
      <h2 class="main-title">手势识别</h2>
      <p class="page-desc">支持上传图片识别手势、数字、人脸，自动返回位置与置信度</p>
    </div>

    <!-- 核心功能卡片：统一承载所有内容，避免布局分散 -->
    <el-card shadow="hover" class="gesture-card">
      <!-- 1. 图片上传区域：新增引导文本，优化交互提示 -->
      <div class="section-wrapper upload-wrapper">
        <h3 class="section-heading">
          <i class="el-icon-upload section-icon"></i>
          上传手势图片
        </h3>
        <el-upload
          class="upload-area"
          action="#"
          :auto-upload="false"
          :on-change="handleFileChange"
          :before-upload="beforeUpload"
          accept="image/jpg,image/png,image/bmp,image/jpeg"
          list-type="picture-card"
          drag
          :disabled="isLoading"
        >
          <i class="el-icon-plus upload-plus"></i>
          <div class="el-upload__text">
            <em>点击上传</em> 或 <em>拖拽图片</em> 至此处
          </div>
          <div class="el-upload__tip upload-tip">
            支持格式：JPG/PNG/BMP | 最大尺寸：4MB | 建议：清晰拍摄单/多手势
          </div>
        </el-upload>
      </div>

      <!-- 2. 图片预览区域：标题+清空按钮同行，优化空间利用 -->
      <div class="section-wrapper preview-wrapper" v-if="previewUrl || (fileList.length > 0 && !previewUrl)">
        <div class="section-heading-bar">
          <h3 class="section-heading">
            <i class="el-icon-picture section-icon"></i>
            图片预览
          </h3>
          <!-- 新增清空按钮：方便重新上传 -->
          <el-button 
            type="text" 
            icon="el-icon-close" 
            @click="clearPreview"
            :disabled="isLoading"
            class="clear-btn"
            v-if="previewUrl"
          >
            清空图片
          </el-button>
        </div>

        <!-- 预览图容器：居中+阴影，提升视觉聚焦 -->
        <div class="preview-container" v-if="previewUrl">
          <img 
            :src="previewUrl" 
            class="preview-img" 
            alt="手势图片预览" 
            loading="lazy"
          >
          <!-- 识别按钮：紧贴预览图，操作路径更短 -->
          <el-button 
            type="primary" 
            icon="el-icon-search" 
            @click="doRecognize"
            :loading="isLoading"
            class="recognize-btn"
          >
            开始识别
          </el-button>
        </div>

        <!-- 清空后空状态：避免页面空白 -->
        <el-empty 
          description="已清空图片，请重新上传" 
          class="empty-state"
          v-if="!previewUrl && fileList.length > 0"
        ></el-empty>
      </div>

      <!-- 3. 识别结果区域：标题+结果统计同行，优化信息层级 -->
      <div class="section-wrapper result-wrapper" v-if="recognitionResult || (previewUrl && !isLoading && !recognitionResult)">
        <div class="section-heading-bar">
          <h3 class="section-heading">
            <i class="el-icon-data-analysis section-icon"></i>
            识别结果
          </h3>
          <!-- 结果统计：直观展示目标数量 -->
          <span class="result-count" v-if="recognitionResult">
            共识别到 {{ recognitionResult.resultNum }} 个目标
          </span>
        </div>

        <!-- 结果表格：优化列宽+内容换行，适配移动端 -->
        <div class="result-table-container" v-if="recognitionResult">
          <el-table :data="recognitionResult.resultList" border stripe size="mini">
            <el-table-column label="目标类型" prop="classname" width="160">
              <template #default="scope">
                <span v-if="scope.row.classname === 'Face'">人脸</span>
                <span v-else-if="scope.row.classname.startsWith('Heart')">双手比心</span>
                <span v-else-if="scope.row.classname.match(/^[0-9]$|^One|Two|Three|Four|Five|Six|Seven|Eight|Nine$/)">数字{{ getNumberLabel(scope.row.classname) }}</span>
                <span v-else>{{ getGestureLabel(scope.row.classname) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="置信度" prop="probability" width="120">
              <template #default="scope">{{ (scope.row.probability * 100).toFixed(2) }}%</template>
            </el-table-column>
            <el-table-column label="位置信息">
              <template #default="scope">
                <div class="position-text">
                  上: {{ scope.row.top }}px<br>
                  左: {{ scope.row.left }}px<br>
                  宽: {{ scope.row.width }}px<br>
                  高: {{ scope.row.height }}px
                </div>
              </template>
            </el-table-column>
          </el-table>

          <!-- 日志ID：调整位置，增加复制功能 -->
          <div class="log-id-container">
            <el-tag type="info" class="log-id-tag">
              日志ID: {{ recognitionResult.logId }}
            </el-tag>
            <el-button 
              type="text" 
              icon="el-icon-copy" 
              @click="copyLogId"
              size="mini"
              class="copy-logid-btn"
            >
              复制
            </el-button>
          </div>
        </div>

        <!-- 未识别空状态：引导用户操作 -->
        <el-empty 
          description="暂无识别结果，请点击「开始识别」按钮" 
          class="empty-state"
          v-else-if="previewUrl && !isLoading && !recognitionResult"
        ></el-empty>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { ElMessage, ElEmpty, ElButton, ElTag, ElTooltip } from 'element-plus';
import request from '@/utils/request'; // 若依框架自带的请求工具

// 状态管理（保留原逻辑，新增必要状态）
const previewUrl = ref(''); // 图片预览地址
const base64Image = ref(''); // 图片Base64（不含头）
const isLoading = ref(false); // 加载状态
const recognitionResult = ref(null); // 识别结果
const fileList = ref([]); // 上传文件列表（用于清空状态判断）
const isLogIdCopied = ref(false); // 日志ID复制状态

// ---------------------- 原逻辑保留（仅新增清空、复制功能） ----------------------
/**
 * 文件选择变化（转换为Base64）
 */
const handleFileChange = (file) => {
  fileList.value = [file]; // 记录文件列表，用于清空状态判断
  const reader = new FileReader();
  reader.onload = (e) => {
    const result = e.target.result;
    previewUrl.value = result;
    base64Image.value = result.replace(/data:image\/[^;]+;base64,/, '');
    recognitionResult.value = null; // 新上传图片时清空历史结果
  };
  reader.readAsDataURL(file.raw);
};

/**
 * 上传前校验（格式、大小）
 */
const beforeUpload = (file) => {
  const validTypes = ['image/jpg', 'image/png', 'image/bmp', 'image/jpeg'];
  const isImage = validTypes.includes(file.type);
  const isLt4M = file.size / 1024 / 1024 < 4;

  if (!isImage) {
    ElMessage.error(`请选择${validTypes.map(t => t.split('/')[1].toUpperCase()).join('/')}格式的图片！`);
    return false;
  }
  if (!isLt4M) {
    ElMessage.error('图片大小不能超过4MB！');
    return false;
  }
  return true;
};

/**
 * 发起识别请求
 */
const doRecognize = async () => {
  if (!base64Image.value) {
    ElMessage.warning('请先选择图片！');
    return;
  }

  try {
    isLoading.value = true;
    const response = await request({
      url: '/gesture/recognition/doRecognize',
      method: 'post',
      data: { base64Image: base64Image.value }
    });

    if (response.code === 200) {
      recognitionResult.value = response.data;
      ElMessage.success('识别成功！');
    } else {
      ElMessage.error('识别失败：' + response.msg);
    }
  } catch (error) {
    ElMessage.error('请求异常：' + (error.msg || '网络错误'));
  } finally {
    isLoading.value = false;
  }
};

/**
 * 转换数字手势标签
 */
const getNumberLabel = computed(() => {
  return (classname) => {
    const numberMap = {
      'One': '1', 'Two': '2', 'Three': '3', 'Four': '4', 'Five': '5',
      'Six': '6', 'Seven': '7', 'Eight': '8', 'Nine': '9'
    };
    return numberMap[classname] || classname;
  };
});

/**
 * 转换手势标签
 */
const getGestureLabel = computed(() => {
  return (classname) => {
    const gestureMap = {
      'Fist': '拳头', 'OK': 'OK', 'Prayer': '祈祷', 'Congratulation': '作揖',
      'Honour': '作别', 'Heart_single': '单手比心', 'Thumb_up': '点赞',
      'Thumb_down': 'Diss', 'ILY': '我爱你', 'Palm_up': '掌心向上',
      'Heart_1': '双手比心（样式1）', 'Heart_2': '双手比心（样式2）',
      'Heart_3': '双手比心（样式3）', 'Rock': 'Rock（摇滚手势）',
      'Insult': '竖中指', 'other': '其他手势'
    };
    return gestureMap[classname] || classname;
  };
});

// ---------------------- 新增：布局配套功能 ----------------------
/**
 * 清空预览（重置图片与结果）
 */
const clearPreview = () => {
  previewUrl.value = '';
  base64Image.value = '';
  recognitionResult.value = '';
  fileList.value = [];
  ElMessage.success('图片已清空');
};

/**
 * 复制日志ID（提升问题定位效率）
 */
const copyLogId = () => {
  if (!recognitionResult.value?.logId) return;

  navigator.clipboard.writeText(recognitionResult.value.logId)
    .then(() => {
      isLogIdCopied.value = true;
      ElMessage.success('日志ID已复制');
      setTimeout(() => isLogIdCopied.value = false, 2000);
    })
    .catch(() => {
      ElMessage.error('复制失败，请手动复制');
    });
};
</script>

<style scoped>
/* 页面容器：全屏居中+背景色，避免内容贴边 */
.gesture-page-container {
  padding: 30px 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
  box-sizing: border-box;
}

/* 页面主标题：居中+上下间距，强化主题 */
.page-header {
  text-align: center;
  margin-bottom: 30px;
}

.main-title {
  font-size: 24px;
  font-weight: 600;
  color: #1f2937;
  margin: 0 0 8px;
}

.page-desc {
  font-size: 14px;
  color: #6b7280;
  margin: 0;
}

/* 核心卡片：限制最大宽度+居中，避免宽屏上内容过散 */
.gesture-card {
  max-width: 1000px;
  margin: 0 auto;
  border-radius: 8px;
  padding: 25px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.06) !important;
}

/* 区域通用样式：统一间距+分隔感 */
.section-wrapper {
  margin-bottom: 35px;
  padding-bottom: 20px;
  border-bottom: 1px solid #f0f2f5;
}

/* 最后一个区域去掉下边框 */
.section-wrapper:last-child {
  margin-bottom: 10px;
  padding-bottom: 0;
  border-bottom: none;
}

/* 区域标题栏：标题+功能按钮同行，优化空间 */
.section-heading-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 18px;
}

/* 区域标题：带图标+统一样式，提升辨识度 */
.section-heading {
  font-size: 16px;
  font-weight: 500;
  color: #2563eb;
  margin: 0;
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 区域图标：统一颜色+大小 */
.section-icon {
  font-size: 18px;
  color: #2563eb;
}

/* 上传区域：优化提示文本样式 */
.upload-area {
  margin-top: 8px;
}

.upload-plus {
  font-size: 24px;
}

.upload-tip {
  font-size: 12px;
  color: #6b7280;
  margin-top: 8px;
}

/* 预览区域：居中+阴影，提升视觉聚焦 */
.preview-container {
  text-align: center;
}

.preview-img {
  max-width: 100%;
  max-height: 450px;
  border: 1px solid #e5e7eb;
  border-radius: 6px;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.08);
  margin-bottom: 20px;
}

/* 识别按钮：优化大小+间距 */
.recognize-btn {
  padding: 8px 24px;
  font-size: 14px;
}

/* 清空按钮：hover变色，提升交互反馈 */
.clear-btn {
  color: #6b7280;
  transition: color 0.3s;
}

.clear-btn:hover {
  color: #ef4444;
}

/* 结果区域：表格容器+滚动适配 */
.result-table-container {
  margin-top: 8px;
}

/* 位置信息：换行显示，避免横向溢出 */
.position-text {
  font-size: 12px;
  color: #6b7280;
  line-height: 1.6;
}

/* 结果统计：统一颜色+大小 */
.result-count {
  font-size: 14px;
  color: #6b7280;
}

/* 日志ID容器：同行显示+间距 */
.log-id-container {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-top: 12px;
}

/* 日志ID标签：优化大小+内边距 */
.log-id-tag {
  font-size: 12px;
  padding: 4px 12px;
}

/* 复制按钮：统一大小+颜色 */
.copy-logid-btn {
  color: #2563eb;
  font-size: 12px;
}

/* 空状态：统一间距，避免页面空白 */
.empty-state {
  margin: 40px 0;
}

/* 响应式适配：移动端优化 */
@media (max-width: 768px) {
  .gesture-page-container {
    padding: 20px 10px;
  }

  .gesture-card {
    padding: 18px;
  }

  .main-title {
    font-size: 20px;
  }

  .section-heading {
    font-size: 15px;
  }

  .preview-img {
    max-height: 350px;
  }

  .section-heading-bar {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
}
</style>